//
//  MainViewController.swift
//  Weibo
//
//  Created by 张婷 on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

// MARK: 主控制器
class MainViewController: UITabBarController {
    
    // MARK: 监听方法
    /// 只使用 private 修饰，运行循环无法正确发送消息，找不到方法，崩溃
    /// 用 @objc 修饰之后，保证运行循环能够发送消息，即使是用 private修饰
    @objc private func clickComposedButton() {
        print("点我了")
    }
    
    // MARK: 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        setupComposedButton()
    }
    
    // 在 viewWillAppear 这个方法里面 才会加载 tabar 的子控件
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tabBar.bringSubviewToFront(composedButton)
    }
    
    // MARK: - 懒加载控件
    // 一个闭包用来描述 composedButton
    private lazy var composedButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
   }

// MARK: 设置界面
extension MainViewController {
    
    /// 添加撰写按钮
    private func setupComposedButton() {
        
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
    }
    
    /// 添加所有的控制器
    private func addChildViewControllers() {
        
        // 设置 TintColor 图片渲染颜色
        tabBar.tintColor = UIColor.orangeColor()
        
        addChildViewController(HomeViewController(), title: "首页", imgeName: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", imgeName: "tabbar_message_center")
        
        // 添加 compose
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverViewController(), title: "发现", imgeName:
            "tabbar_discover")
        addChildViewController(ProfileViewController(), title: "我", imgeName: "tabbar_profile")
    }
    
    /// 添加子控制器
    private func addChildViewController(childController: UIViewController, title: String, imgeName: String) {
        
        childController.title = title
        childController.tabBarItem.image = UIImage(named: imgeName)
        
        let nav = UINavigationController(rootViewController: childController)
        addChildViewController(nav)
    }
}
